let _TempRandom;

function androidBridge() {
	if (window.WebViewJavascriptBridge) {
		return;
	}

	let messagingIframe;
	let sendMessageQueue = [];
	let receiveMessageQueue = [];
	let messageHandlers = {};

	let CUSTOM_PROTOCOL_SCHEME = "yy";
	let QUEUE_HAS_MESSAGE = "__QUEUE_MESSAGE__/";

	let responseCallbacks = {};
	let uniqueId = 1;

	function _createQueueReadyIframe(doc) {
		messagingIframe = doc.createElement("iframe");
		messagingIframe.style.display = "none";
		doc.documentElement.appendChild(messagingIframe);
	}

	function registerHandler(handlerName, handler) {
		messageHandlers[handlerName] = handler;
	}

	//sendMessage add message, 触发native处理 sendMessage
	function _doSend(message, responseCallback) {
		if (responseCallback) {
			let callbackId =
				"cb_" + uniqueId++ + "_" + new Date().getTime() + "_" + _TempRandom;
			responseCallbacks[callbackId] = responseCallback;
			message.callbackId = callbackId;
		}
		sendMessageQueue.push(message);
		messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + "://" + QUEUE_HAS_MESSAGE;
	}

	function send(data, responseCallback) {
		_doSend(
			{
				data: data
			},
			responseCallback
		);
	}

	function callHandler(handlerName, data, responseCallback) {
		_TempRandom = Math.round(Math.random() * 1000000);

		setTimeout(() => {}, 2);
		_doSend(
			{
				handlerName: handlerName,
				data: data
			},
			responseCallback
		);
	}

	// 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容
	function _fetchQueue() {
		let messageQueueString = JSON.stringify(sendMessageQueue);
		sendMessageQueue = [];
		// console.log(messageQueueString);
		//android can't read directly the return data, so we can reload iframe src to communicate with java
		messagingIframe.src =
			CUSTOM_PROTOCOL_SCHEME +
			"://return/_fetchQueue/" +
			encodeURIComponent(messageQueueString);
	}

	//提供给native使用,
	function _dispatchMessageFromNative(messageJSON) {
		setTimeout(function () {
			let message = {};
			try {
				message = JSON.parse(messageJSON);
			} catch (error) {
				throw new Error(error);
			}
			let responseCallback;
			//java call finished, now need to call js callback function
			if (message.responseId) {
				responseCallback = responseCallbacks[message.responseId];
				if (!responseCallback) {
					return;
				}
				responseCallback(JSON.parse(message.responseData));
				delete responseCallbacks[message.responseId];
			} else {
				//直接发送
				if (message.callbackId) {
					let callbackResponseId = message.callbackId;
					responseCallback = function (responseData) {
						_doSend({
							responseId: callbackResponseId,
							responseData: responseData
						});
					};
				}
				let handler = window.WebViewJavascriptBridge._messageHandler;
				if (message.handlerName) {
					handler = messageHandlers[message.handlerName];
				}
				//查找指定handler
				try {
					handler(message.data, responseCallback);
				} catch (exception) {
					throw new Error(exception);
				}
			}
		});
	}

	//提供给native调用,receiveMessageQueue 在会在页面加载完后赋值为null,所以
	function _handleMessageFromNative(messageJSON) {
		if (receiveMessageQueue && receiveMessageQueue.length > 0) {
			receiveMessageQueue.push(messageJSON);
		} else {
			_dispatchMessageFromNative(messageJSON);
		}
	}

	//set default messageHandler
	function init(messageHandler) {
		if (window.WebViewJavascriptBridge._messageHandler) {
			throw new Error("WebViewJavascriptBridge.init called twice");
		}
		window.WebViewJavascriptBridge._messageHandler = messageHandler;
		let receivedMessages = receiveMessageQueue;
		receiveMessageQueue = null;
		for (let i = 0; i < receivedMessages.length; i++) {
			_dispatchMessageFromNative(receivedMessages[i]);
		}
	}

	let WebViewJavascriptBridge = (window.WebViewJavascriptBridge = {
		init: init,
		send: send,
		registerHandler: registerHandler,
		callHandler: callHandler,
		_fetchQueue: _fetchQueue,
		_handleMessageFromNative: _handleMessageFromNative
	});

	let doc = document;
	_createQueueReadyIframe(doc);
	let readyEvent = doc.createEvent("Events");
	readyEvent.initEvent("WebViewJavascriptBridgeReady");
	readyEvent.bridge = WebViewJavascriptBridge;
	doc.dispatchEvent(readyEvent);
}

function iosBridge(callback) {
	if (window.WebViewJavascriptBridge) {
		return callback(window.WebViewJavascriptBridge);
	}
	if (window.WVJBCallbacks) {
		return window.WVJBCallbacks.push(callback);
	}
	window.WVJBCallbacks = [callback];
	let WVJBIframe = document.createElement("iframe");
	WVJBIframe.style.display = "none";
	WVJBIframe.src = "https://__bridge_loaded__";
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function () {
		document.documentElement.removeChild(WVJBIframe);
	}, 0);
}
export { androidBridge, iosBridge };
